﻿using AppFlat.Application.IService;
using AppFlat.Domain.Models;
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Threading.Tasks;
using System.Web.Http;

namespace AppFlat.UI.WebApi.Controllers
{
    public class CategorysController : ApiController
    {
        public ICategoryService CateApp { get; set; }

        // dtree数据
        public async Task<IHttpActionResult> GetList()
        {
            var result = await CateApp.GetEntities()
                .Select(n=>new { id=n.Id, title=n.Name, parentId=n.ParentId})
                .ToListAsync();
            return Json(new { code=0, msg="",data=result});
        }


        public async Task<IHttpActionResult> Put([FromBody]Category category)
        {
            if (ModelState.IsValid)
            {
                await CateApp.UpdateAsync(category);
                return Ok("修改完成");
            }
            return BadRequest("格式不正确！");
        }

        public async Task<IHttpActionResult> Post([FromBody]Category category)
        {
            if (ModelState.IsValid)
            {
                await CateApp.AddAsync(category);
                return Ok("添加完成");
            }
            return BadRequest("格式不正确！");
        }

        public async Task<IHttpActionResult> Delete(int? id)
        {
            if (!id.HasValue)
                return BadRequest("请选择类别！");

            var result = await CateApp.DeleteAsync(new Category() { Id = id.Value,Name="" });
            if (result)
                return Ok("修改完成");
            
            return NotFound();
        }

        //批量删除
        public async Task<IHttpActionResult> DeleteByIds([FromUri] int[] ids)
        {
            return Json(ids);
        }
    }
}
